import { AccurateMath } from "../../../utils/accurateMath.js"
import { Api } from "../../../utils/api.js"
import { Http } from '../../../utils/http.js'
let accurateMath = new AccurateMath()
let http = new Http()
var isBuy = 0//是否是直接购买

// pages/mall/pay/pay.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: null,
    userCarts: [],      //购物车列表
    availableCoupon: null,
    amount: 0,       //商品总价
    pricePay: 0,        //待支付价格
    couponNum: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var userCarts = JSON.parse(options.orderList)
    isBuy = options.isBuy
    var amount = 0
    userCarts.forEach(item => {
      amount = accurateMath.accAdd(amount, item.priceAmount)
    })
    this.setData({
      userCarts: userCarts,
      amount: amount,
      pricePay: amount
    })
    this.getCouponNum()
    this.getAddressLastSelect()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 自定义方法
   */
  goAddress: function () {
    var that = this
    wx.chooseAddress({
      success: function (res) {
        if (res.errMsg == 'chooseAddress:ok') {
          that.setData({
            address: res
          })
          wx.setStorage({
            key: 'addressLastSelect',
            data: JSON.stringify(res)
          })
        }
      },
      fail: function (res) {
        if (res.errMsg == 'chooseAddress:fail auth deny') {
          wx.showModal({
            title: '提示',
            content: '请到设置中允许微信打开',
            confirmText: '去设置',
            success: function (res) {
              if (res.confirm) {
                wx.openSetting({
                  success: function (res) {

                  },
                  fail: function (res) {
                    wx.showToast({
                      title: '打开设置失败，请手动打开',
                      icon: 'none'
                    })
                  }
                })
              }
            }
          })
        }
      }
    })
  },
  getAddressLastSelect: function () {
    var that = this
    wx.getStorage({
      key: 'addressLastSelect',
      success: function(res) {
        that.setData({
          address: JSON.parse(res.data)
        })
      }
    })
  },

  pay: function () {
    var address = this.data.address
    var userCarts = this.data.userCarts
    var coupon = this.data.availableCoupon
    var that = this
    if (address != null) {
      if (userCarts.length > 0) {
        let goods = []
        let cartIds = []
        userCarts.forEach(function (v, i, arr) {
          let item = {}
          item.goodsId = arr[i].goods.id
          item.number = arr[i].number
          goods.push(item)
          if(isBuy != 1){
            cartIds.push(arr[i].id)
          }
        })
        let data = {}
        data.goods = JSON.stringify(goods)
        data.cartIds = cartIds.join(',')
        data.logisticsName = address.userName
        data.logisticsPhone = address.telNumber
        data.logisticsAddress = address.provinceName + address.cityName + address.countyName + address.detailInfo
        let shareId = this.getShareId()
        if (shareId > 0) {
          data.shareId = shareId
        }
        if (coupon != null) {
          data.userCouponId = coupon.id
        }
        wx.showLoading({
          title: '支付中...',
        })
        http.sendHttp(Api.pay_order, {
          data: data,
          success: function (res) {
            var orderNo = res.data.obj.orderNo
            wx.requestPayment({
              timeStamp: res.data.obj.timeStamp,
              nonceStr: res.data.obj.nonceStr,
              package: res.data.obj.package,
              signType: res.data.obj.signType,
              paySign: res.data.obj.paySign,
              success: function (res) {
                that.queryOrder(orderNo)
                wx.redirectTo({
                  url: '/pages/mall/paySuccess/paySuccess?success=1&orderNo=' + orderNo,
                })
              },
              fail: function (res) {
                wx.redirectTo({
                  url: '/pages/mall/paySuccess/paySuccess?success=0',
                })
              }
            })
          },
          finish: function () {
            wx.hideLoading()
          }
        }, 'POST')
      } else {
        wx.showToast({
          title: '请选择下单商品',
          icon: 'none'
        })
      }
    } else {
      wx.showToast({
        title: '请选择收货地址',
        icon: 'none'
      })
    }
  },

  queryOrder: function(orderNo) {
    http.sendHttp(Api.query_order, {
      data: {
        orderNo: orderNo
      },
      success: function (res) {
        
      }
    }, 'POST')
  },

  setAvailableCoupons: function(availableCoupon){
    //选择优惠券回调
    var pricePay = 0.0
    if(availableCoupon == null){
      pricePay = this.data.amount
    }else{
      pricePay = accurateMath.accSub(this.data.amount, availableCoupon.coupon.nomimalPrice)
    }
    this.setData({
      availableCoupon: availableCoupon,
      pricePay: pricePay
    })

  },

  goCoupon: function () {
    var that = this
    wx.navigateTo({
      url: '/pages/mall/availableCoupon/availableCoupon?amount=' + that.data.amount + "&userCoupon=" + (this.data.availableCoupon != null ? "1" : "0"),
    })
  },

  getShareId: function () {
    var shareId = wx.getStorageSync("shareId")
    if (shareId == undefined || shareId == null) {
      shareId = 0
    }
    return shareId
  },

  getCouponNum: function(){
    var amount = this.data.amount
    var that = this
    // 获取可用优惠券数量
    http.sendHttp(Api.get_us_able_num ,{
      data: {
        amount: amount
      },
      success: function(res){
        that.setData({
          couponNum: res.data.obj.count
        })
      }
    })
  }

})